package org.bugstat.renderers.html;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class ZipUtils
{
    private static final int BUFFER = 1024 * 1024;

    public static void unzip(File inFile, File outFolder) throws IOException
    {
        BufferedOutputStream out = null;
        ZipInputStream in = new ZipInputStream(new BufferedInputStream(new FileInputStream(inFile)));
        ZipEntry entry;
        while ( (entry = in.getNextEntry()) != null )
        {
            if ( entry.isDirectory() )
            {
                // Create output folder
                final File outputFolder = new File( outFolder, entry.getName() );
                outputFolder.mkdirs();
            }
            else
            {
                int count;
                byte data[] = new byte[BUFFER];
    
                // write the files to the disk
                final File outputFile = new File( outFolder, entry.getName() );
                outFolder.createNewFile();
                
                out = new BufferedOutputStream(new FileOutputStream(outputFile), BUFFER);
    
                while ( (count = in.read(data, 0, BUFFER)) != -1 )
                {
                    out.write(data, 0, count);
                }
    
                cleanUp(out);
            }
        }

        cleanUp(in);
    }

    private static void cleanUp(InputStream in) throws IOException
    {
        in.close();
    }

    private static void cleanUp(OutputStream out) throws IOException
    {
        out.flush();
        out.close();
    }
}
